
import { getCookie, removeCookie, setCookie } from '@/utils/cache'
import * as api from '@/api/index'
import router from '@/router'
const user = {
  state: {
    userInfo: {}, // 用户信息
    userType: '00', // 用户类型：00-系统用户 01-VIP用户
    type: '1', // 用户类型：1-PC  2-APP  3-大客户
    token: getCookie(import.meta.env.VITE_VUETOKEN_STR),
    roles: [],
    permissions: [], // 权限标识
    themeColors: {
      primaryColor: '#0278b1',
      menuBgColor: '#284876',
      menuIconColor: '#909399',
      menuCheckedColor: '#0278b1',
      menuTextColor: '#cccccc'
    }
  },
  getters: {
    userInfo: state => state.userInfo,
    userType: state => state.userType,
    type: state => state.type,
    token: state => state.token,
    roles: state => state.roles,
    permissions: state => state.permissions,
    themeColors: state => state.themeColors
  },
  mutations: {
    SET_USERINFO: (state, data) => {
      state.userInfo = data
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, data) => {
      state.permissions = data
    },
    SET_THEME_COLORS: (state, data) => {
      state.themeColors = data
    }
  },
  actions: {
    // 登出
    LogOut({ commit }, data) {
      return new Promise(async (resolve) => {
        logOut(commit, data, resolve)
      })
    },
    // 清空
    LogInit({ commit }) {
      return new Promise((resolve) => {
        removeCookie(import.meta.env.VITE_VUETOKEN_STR)
        commit('SET_USERINFO', {})
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeCookie(import.meta.env.VITE_VUETENANT_STR)
        resolve()
      })
    },
    setThemeColors({ commit }, data) {
      return new Promise((resolve) => {
        setCookie('TOKEN_RQ_THEME_COLORS', JSON.stringify(data))
        commit('SET_THEME_COLORS', data)
        resolve()
      })
    }
  }
}

function logOut(commit, data, resolve) {
  api.default.user.logout(data).then(res => {
    removeCookie(import.meta.env.VITE_VUETOKEN_STR)
    commit('SET_USERINFO', {})
    commit('SET_ROLES', [])
    commit('SET_PERMISSIONS', [])
    removeCookie(import.meta.env.VITE_VUETENANT_STR)
    router.replace('/login')
    resolve()
  })
}

export default user
